﻿using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NewRetail.Application.Components.PrintTask;
using NewRetail.Application.Components.PrintTask.Entity;
using NewRetail.Application.Components.PrintTask.Model;
using NewRetail.Application.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;

namespace NewRetail.Api.Controllers
{
    [NewRetailRoute("print-authorization-code-task")]
    public class PrintAuthorizationCodeTaskController : BaseController<PrintAuthorizationCodeTaskEntity>
    {
        private readonly IPrintAuthorizationCodeTaskService printAuthorizationCodeTaskService;

        public PrintAuthorizationCodeTaskController(IPrintAuthorizationCodeTaskService printAuthorizationCodeTaskService)
        {
            this.printAuthorizationCodeTaskService = printAuthorizationCodeTaskService;
        }

        #region 根据仓库Id查询所有的授权码打印任务
        [HttpPost("query-all-authcode-need-print")]
        public async Task<ResponseEntity<PrintAuthCodeTaskDataResultDto[]>> QueryByReceiptNo([FromBody] PrintAuthCodeTaskQueryAllInputDto dto)
        {
            dto.Should().NotBeNull();
            dto.warehouseId.Should().NotBeNullOrEmpty();

            var query = this.SingleStoreService.ApplyToQueryable(this.Repo);
            var data = await query.Where(x => x.printTag == 0 && x.warehouseID == dto.warehouseId).ToArrayAsync();
            var result = new List<PrintAuthCodeTaskDataResultDto>();
            foreach (var item in data)
                result.Add(new PrintAuthCodeTaskDataResultDto() { authorizationCode = item.authorizationCode, cashierName = item.cashierName });
            return new ResponseEntity<PrintAuthCodeTaskDataResultDto[]>().SetData(result.ToArray());
        }
        #endregion

        #region 更新打印任务的记录状态，将0变成1
        [HttpPost("update-authorization-code-printtag")]
        public async Task<ResponseEntity<string>> UpdatePrintAuthorizationCodeTagByWarehouseId([FromBody] PrintAuthorizationCodeUpdateDto dto)
        {
            dto.Should().NotBeNull();
            dto.warehouseId.Should().NotBeNullOrEmpty();
            var ret = new ResponseEntity<string>();
            var result = await this.printAuthorizationCodeTaskService.UpdatePrintAuthorizationCodeTagByWarehouseId(dto.warehouseId);

            if (string.IsNullOrEmpty(result.Item1))
                ret.SetError("更新失败！" + result.Item2);
            else
                ret.SetData("更新成功");

            return ret;
        }
        #endregion
    }
}
